using System.Collections.ObjectModel;
using System.Windows.Input;
using demo001.Models;
using demo001.Services;

namespace demo001
{
    public partial class MainPage : ContentPage
    {
        //全局变量视频操作对象
        private readonly VideoService _videoService;
        //搜索已的视频列表
        private ObservableCollection<VideoViewModel> _searchResults = new ObservableCollection<VideoViewModel>();
        //已订阅的视频列表
        private ObservableCollection<VideoViewModel> _subscribedVideos = new ObservableCollection<VideoViewModel>();
        //最后一次搜索的关键词的字符串变量
        private string _lastSearchQuery = string.Empty;

        /// <summary>
        /// 搜索结果集合
        /// </summary>
        public ObservableCollection<VideoViewModel> SearchResults
        {
            get => _searchResults;// 获取结果集合
            set
            {
                _searchResults = value;// 设置新的结果集合
                OnPropertyChanged(nameof(SearchResults));// 通知UI更新
            }
        }

        /// <summary>
        /// 已订阅视频集合
        /// </summary>
        public ObservableCollection<VideoViewModel> SubscribedVideos
        {
            get => _subscribedVideos;// 获取结果集合
            set
            {
                _subscribedVideos = value;// 设置新的结果集合
                OnPropertyChanged(nameof(SubscribedVideos));// 通知UI更新
            }
        }

        /// <summary>
        /// 搜索命令
        /// </summary>
        public ICommand SearchCommand { get; }

        /// <summary>
        /// 订阅命令
        /// </summary>
        public ICommand SubscribeCommand { get; }

        /// <summary>
        /// 取消订阅命令
        /// </summary>
        public ICommand UnsubscribeCommand { get; }

        /// <summary>
        /// 播放命令
        /// </summary>
        public ICommand PlayCommand { get; }

        /// <summary>
        /// 订阅搜索命令
        /// </summary>
        public ICommand SubscriptionSearchCommand { get; }

        /// <summary>
        /// 排序选项变更命令
        /// </summary>
        public ICommand SortOptionChangedCommand { get; }

        /// <summary>
        /// 退出登录命令
        /// </summary>
        public ICommand LogoutCommand { get; }

        /// <summary>
        /// 构造函数
        /// </summary>
        public MainPage()
        {
            InitializeComponent();
            //设置 BindingContext 为当前页面类实例（this），使得 XAML 中的绑定表达式可以直接访问该类的公共属性和命令
            BindingContext = this;

            // 初始化服务
            _videoService = new VideoService();

            // 初始化命令 
            //SearchCommand 是一个实现了 ICommand 接口的命令对象
            //它将 UI 事件（如按钮点击）与业务逻辑方法（SearchVideosAsync）连接起来
            SearchCommand = new Command(async () => await SearchVideosAsync());
            SubscribeCommand = new Command<VideoViewModel>(async (video) => await SubscribeVideoAsync(video));
            UnsubscribeCommand = new Command<VideoViewModel>(async (video) => await UnsubscribeVideoAsync(video));
            PlayCommand = new Command<VideoViewModel>(PlayVideo);
            SubscriptionSearchCommand = new Command(() => SearchSubscribedVideos(SubscriptionSearchEntry.Text?.Trim() ?? string.Empty));
            SortOptionChangedCommand = new Command(ApplySortOption);
            LogoutCommand = new Command(async () => await LogoutAsync());

            // 设置默认排序选项
            SortPicker.SelectedIndex = 0;

            // 加载已订阅视频
            LoadSubscribedVideos();
        }


        private async void OnSearchClicked(object sender, EventArgs e)
        {
           
            await SearchVideosAsync();
        }
        /// <summary>
        /// 搜索视频
        /// </summary>
        private async Task SearchVideosAsync()
        {
            try
            {
                string query = SearchEntry.Text?.Trim() ?? string.Empty;
                if (string.IsNullOrWhiteSpace(query))
                {
                    await DisplayAlert("提示", "请输入搜索关键词", "确定");
                    return;
                }

                _lastSearchQuery = query;
                SearchResults.Clear();

                // 显示加载指示器
                IsBusy = true;

                // 搜索视频
                var results = await _videoService.SearchVideosAsync(query);
                //var results2 = await _videoService.SearchVideosAsync2(query);


                // 更新UI
                foreach (var video in results)
                {
                    SearchResults.Add(video);
                }

                if (SearchResults.Count == 0)
                {
                    await DisplayAlert("提示", "未找到匹配的视频", "确定");
                }
            }
            catch (Exception ex)
            {
                await DisplayAlert("错误", $"搜索视频时出错: {ex.Message}", "确定");
            }
            finally
            {
                IsBusy = false;
            }
        }

       

        /// <summary>
        /// 取消订阅视频
        /// </summary>
        private async Task UnsubscribeVideoAsync(VideoViewModel video)
        {
            try
            {
                if (video == null) return;

                bool confirm = await DisplayAlert("确认", $"确定要取消订阅视频 \"{video.Title}\" 吗?", "确定", "取消");
                if (!confirm) return;

                bool success = await _videoService.UnsubscribeVideoAsync(video.VideoId);
                if (success)
                {
                    // 从列表中移除
                    SubscribedVideos.Remove(video);
                    
                    // 更新搜索结果中的订阅状态
                    var searchVideo = SearchResults.FirstOrDefault(v => v.VideoId == video.VideoId);
                    if (searchVideo != null)
                    {
                        searchVideo.IsSubscribed = false;
                    }
                    
                    await DisplayAlert("成功", $"已取消订阅视频: {video.Title}", "确定");
                }
                else
                {
                    await DisplayAlert("错误", "取消订阅视频失败", "确定");
                }
            }
            catch (Exception ex)
            {
                await DisplayAlert("错误", $"取消订阅视频时出错: {ex.Message}", "确定");
            }
        }
        /// <summary>
        /// 订阅视频
        /// </summary>
        private async Task SubscribeVideoAsync(VideoViewModel video)
        {
            try
            {
                if (video == null) return;

                bool success = await _videoService.SubscribeVideoAsync(video);
                if (success)
                {
                    // 更新UI状态
                    video.IsSubscribed = true;

                    // 刷新已订阅视频列表
                    LoadSubscribedVideos();

                    await DisplayAlert("成功", $"已成功订阅视频: {video.Title}", "确定");
                }
                else
                {
                    await DisplayAlert("错误", "订阅视频失败", "确定");
                }
            }
            catch (Exception ex)
            {
                await DisplayAlert("错误", $"订阅视频时出错: {ex.Message}", "确定");
            }
        }
        /// <summary>
        /// 播放视频
        /// </summary>
        private async void PlayVideo(VideoViewModel video)
        {
            try 
            {
                // 检查视频是否已下载
                if (string.IsNullOrEmpty(video.LocalFilePath) || !File.Exists(video.LocalFilePath))
                {
                    bool download = await DisplayAlert("提示", 
                        "视频未下载，是否立即下载并播放？", 
                        "下载并播放", "取消");
                    
                    if (download)
                    {
                        // 订阅并下载视频
                        await SubscribeVideoAsync(video);
                        
                        // 等待下载完成
                        while (video.IsDownloading)
                        {
                            await Task.Delay(100);
                        }
                    }
                    else 
                    {
                        return;
                    }
                }

                // 确保文件存在且可访问
                if (!File.Exists(video.LocalFilePath))
                {
                    await DisplayAlert("错误", "视频文件不存在", "确定");
                    return;
                }

                // 跳转到视频播放页面
                await Navigation.PushAsync(new VideoPlayerPage(video));
            }
            catch (Exception ex)
            {
                await DisplayAlert("错误", $"播放视频时出错: {ex.Message}", "确定");
            }
        }

        /// <summary>
        /// 加载已订阅视频
        /// </summary>
        private void LoadSubscribedVideos()
        {
            SubscribedVideos.Clear();
            foreach (var video in _videoService.SubscribedVideos)
            {
                SubscribedVideos.Add(video);
            }
        }

        /// <summary>
        /// 处理订阅搜索文本变更事件
        /// </summary>
        private void OnSubscriptionSearchTextChanged(object sender, TextChangedEventArgs e)
        {
            // 实时搜索可以在这里实现
            // 注意：这个事件处理器保留，因为TextChanged事件更适合用于实时搜索
            // 如果需要完全统一为命令模式，可以使用Behaviors实现TextChanged的命令绑定
        }
        
        /// <summary>
        /// 处理排序选项变更事件 - 事件处理器调用命令
        /// </summary>
        private void OnSortOptionChanged(object sender, EventArgs e)
        {
            // 调用命令执行排序逻辑
            SortOptionChangedCommand.Execute(null);
        }

        /// <summary>
        /// 搜索已订阅视频
        /// </summary>
        private void SearchSubscribedVideos(string query)
        {
            var results = _videoService.SearchSubscribedVideos(query);
            
            SubscribedVideos.Clear();
            foreach (var video in results)
            {
                SubscribedVideos.Add(video);
            }
        }

        /// <summary>
        /// 应用排序选项
        /// </summary>
        private void ApplySortOption()
        {
            VideoSortOption sortOption;
            
            switch (SortPicker.SelectedIndex)
            {
                case 0:
                    sortOption = VideoSortOption.TitleAscending;
                    break;
                case 1:
                    sortOption = VideoSortOption.TitleDescending;
                    break;
                case 2:
                    sortOption = VideoSortOption.DateAscending;
                    break;
                case 3:
                    sortOption = VideoSortOption.DateDescending;
                    break;
                default:
                    sortOption = VideoSortOption.TitleAscending;
                    break;
            }
            
            var sortedVideos = _videoService.SortSubscribedVideos(sortOption);
            
            SubscribedVideos.Clear();
            foreach (var video in sortedVideos)
            {
                SubscribedVideos.Add(video);
            }
        }

        /// <summary>
        /// 退出登录
        /// </summary>
        private async Task LogoutAsync()
        {
            // 显示确认对话框，询问用户是否确定退出登录
            bool answer = await DisplayAlert("确认", "确定要退出登录吗？", "是", "否");
            if (answer)
            {
                // 清除存储的认证令牌，确保用户退出后无法再访问受保护资源
                SecureStorage.Default.Remove("auth_token");
                
                // 导航回登录页面，结束当前会话
                await Navigation.PopToRootAsync();
            }
        }
    }
}